<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title></title>
		<link rel="stylesheet" type="text/css" href="css/mui.min.css" />
		<link rel="stylesheet" type="text/css" href="css/common.css" />
		<link rel="stylesheet" type="text/css" href="index.css" />
	</head>

	<body>
		<div class="header">
			<header class="mui-bar header-main" id="header1">
				<div id="cityarea">
					<i class="iconfont">&#xe687;</i>
					<span id="city" class="mui-ellipsis"></span>
				</div>
				<div class="form-search">
					<!--<i class="iconfont" id="qrcode-icon">&#xe631;</i>-->
					<input type="text" class="mui-input-clear" id="search" placeholder="找帮办、去帮办"/>
				</div>
				<div id="edit">
					<i class="iconfont">&#xe61b;</i>
					<span>发帮办</span>
				</div>
			</header>
			<header class="mui-bar" id="header2">
				<h1 class="mui-title">消息中心</h1>
			</header>
			<header class="mui-bar" id="header3">
				<h1 class="mui-title">我的</h1>
			</header>
		</div>
		<div id="map"></div>
		<nav class="mui-bar mui-bar-tab">
			<a id="defaultTab" class="mui-tab-item mui-active" href="pages/home.html">
				<i class="mui-icon iconfont">&#xe601;</i>
				<span class="mui-tab-label">首页</span>
			</a>
			<a id="artist" class="mui-tab-item" href="pages/artist.html">
				<i class="mui-icon iconfont">&#xe64f;</i>
				<span class="mui-tab-label">找帮办</span>
			</a>
			<a id="artshow" class="mui-tab-item" href="pages/artshow.html">
				<i class="mui-icon iconfont">&#xe63d;</i>
				<span class="mui-tab-label">去帮办</span>
			</a>
			<a id="message" class="mui-tab-item" href="pages/message.html">
				<i class="mui-icon iconfont">&#xe615;<i class="notice"></i></i>
				<span class="mui-tab-label">消息</span>
			</a>
			<a id="me" class="mui-tab-item" href="pages/me.html">
				<i class="mui-icon iconfont">&#xe6a3;</i>
				<span class="mui-tab-label">我的</span>
			</a>
		</nav>
		<script src="js/mui.min.js"></script>
		<!--sdk-->
		<script src="sdk/strophe.js"></script>
		<script src="sdk/easemob.im-1.1.js"></script>
		<script src="sdk/easemob.im-1.1.shim.js"></script>
		<!--兼容老版本sdk需引入此文件-->
		<!--config-->
		<script src="js/easemob.im.config.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/chatMsg.js"></script>
		<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/common.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/user.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" charset="utf-8">
			var header = document.getElementById("header");
			var $notice = $(".notice");
			var city,
				cityElem = document.getElementById("city");
			//mui初始化
			mui.init({
				preloadPages : [{
			    	url : 'pages/artist.html',
			    	id : 'artist.html'
				}, {
			    	url : 'pages/artshow.html',
			    	id : 'artshow.html'
				}]
			});
			var subpages = ['pages/home.html', 'pages/artist.html', 'pages/artshow.html', 'pages/message.html', 'pages/me.html'];
			var subpage_style = {
				top: '44px',
				bottom: '45px'
			};

			var aniShow = {};

			//创建子页面，首个选项卡页面显示，其它均隐藏；
			mui.plusReady(function() {
				// 清空筛选条件
				plus.storage.removeItem('artshowFilter');
				plus.storage.removeItem('artshowKey');
				plus.storage.removeItem('artistFilter');
				plus.storage.removeItem('artistKey');
				
				// 初始化设置
				if(!Common.getUniSetting()) {
					plus.storage.setItem('uniSetting', JSON.stringify(Common.uniSetting));
				}
				
				var self = plus.webview.currentWebview();
				for(var i = 0; i < 5; i++) {
					var temp = {};
					var sub = plus.webview.create(subpages[i], subpages[i], subpage_style);
					if(i > 0) {
						sub.hide();
					} else {
						temp[subpages[i]] = "true";
						mui.extend(aniShow, temp);
					}
					self.append(sub);
				}
				
				// 环信连接对象
				var conn = new Easemob.im.Connection();
				
				// 初始化连接
				conn.init({
					onOpened: function() {
						mui.toast("连接成功");
						conn.setPresence();
					},
					onClosed: function(message) {
						mui.toast("连接关闭");
					},
					// 收到文本消息时的回调函数
					onTextMessage: function(message) {
						mui.fire(self.children()[3], 'reload');
//						var chatPage = plus.webview.getWebviewById('single-chat.html');
//						if(chatPage) { // 在聊天页面 将消息转发至页面
//							console.log(chatPage.releaseId);
//							mui.fire(chatPage, 'getMessage', {
//								msg : message
//							});
//						} else {
//							$notice.show();
//							mui.toast('收到文本消息');
//						}
					},
					// 收到图片消息时的回调函数
					onPictureMessage: function(message) {
					},
					onError: function(message) {
						console.log('错误 ' + JSON.stringify(message));
					},
					// 本机网络连接成功
					onOnline: function() {
						mui.toast('本机网络连接成功');
					},
					// 本机网络掉线
					onOffline: function() {
						mui.toast('本机网络掉线');
					}
				})
				
				// 进入应用初始化连接
				connInit();
				
				// 登录状态改变时确定连接或断开
				document.addEventListener('stateChange', function() {
					connInit();
				})
				
				function connInit() {
					// 登录则打开连接
					if(User.islogin()) {
						conn.open({
							user: User.getMyID(),
							pwd: User.getMyID(),
							appKey: Easemob.im.config.appkey
						});
					} else {
						conn.close();
					}
				}
				
				var localMsg;
				// 添加监听从系统消息中心点击某条消息启动应用事件 （离线消息，本地创建消息）
				// 私聊消息，活动、系统消息
				plus.push.addEventListener("click", function(msg) {
					mui.toast('index触发 click');
					$notice.show();
					if(typeof msg.payload == 'string') {
						localMsg = JSON.parse(msg.payload);
					} else {
						localMsg = msg.payload;
					}
					var msgType, msgInfo;
					msgType = localMsg.msgtype;
					msgInfo = localMsg.msginfo;
					var sName = msg.title;
					/*alert('click->消息内容 > ' + JSON.stringify(msg));
					alert('click->msgType' + '> ' + typeof msgType + '> ' + msgType);
					alert('click->msgInfo' + '> ' + typeof msgInfo + '> ' + msgInfo);
					alert('click->localMsg' + '> ' + typeof localMsg + '> ' + localMsg);*/
					// 创建并打开对应的webview窗口
					switch(msgType) {
						case 1:
							plus.webview.create('pages/single-chat.html', 'chat', {}, {
								releaseId: msgInfo.id,
								sName: sName
							}).show('zoom-out', 200);
							break;
						case 2:
							plus.webview.create('pages/system-messages.html', 'smsg', {}, {}).show('zoom-out', 200);
							break;
						case 3:
							plus.webview.create('pages/activity-messages.html', 'amsg', {}, {}).show('zoom-out', 200);
							break;
						default:
							break;
					}
				}, false);
				
				// 监听在线私信消息 ，本地创建消息
				plus.push.addEventListener("receive", function(msg) {
					mui.toast('index触发 receive');
					if(typeof msg.payload == 'string') {
						localMsg = JSON.parse(msg.payload);
					} else {
						localMsg = msg.payload;
					}
					var msgType, msgInfo;
					// Android 与 iOS消息格式不同 需要分别解析
					if(plus.os.name == 'Android') {
						msgType = localMsg.msgtype;
						msgInfo = localMsg.msginfo;
					} else {
						msgType = JSON.parse(localMsg.payload).msgtype;
						msgInfo = JSON.parse(localMsg.payload).msginfo;
					}
					/*alert('receive->消息内容 > ' + JSON.stringify(msg));
					alert('receive->msgType' + '> ' + typeof msgType + '> ' + msgType);
					alert('receive->msgInfo' + '> ' + typeof msgInfo + '> ' + msgInfo);
					alert('receive->localMsg' + '> ' + typeof localMsg + '> ' + localMsg);*/
					if(msgType == 1) { // 消息类型为私信消息
						// mui.toast('消息类型为私信消息');
						var chatPage = plus.webview.getWebviewById('single-chat.html');
						if(!chatPage) { // 不在聊天窗口（或在与他人聊天的窗口） 创建本地消息 
							$notice.show();
							// 本地创建标准格式消息，用于触发click事件
							var createMsg = { // 这是本地创建标准格式的payload部分
								msgtype: msgType,
								msginfo: {
									id: msgInfo.id, // 对方id
									uname: msgInfo.uname // 对方昵称
								}
							}
							plus.push.createMessage(msgInfo.msgcontent, JSON.stringify(createMsg), {
								title: msgInfo.uname
							});
						} else { // 在当前窗口 将msginfo传至chat.html即可
							mui.fire(chatPage, 'getMessage', {
								msg : localMsg
							});
						}
					} else { // 系统消息，活动消息，直接本地创建标准格式
						var createMsg = { // 这是本地创建标准格式的payload部分
							msgtype: msgType,
							msginfo: {
								id: msgInfo.id, // 对方id
								uname: msgInfo.uname // 对方昵称
							}
						}
						plus.push.createMessage(msgInfo.msgcontent, JSON.stringify(createMsg), {
							title: msgInfo.uname
						});
					}
					if(msg.aps) { // Apple APNS message
						mui.toast("接收到在线APNS消息：");
					} else {
						mui.toast("接收到在线透传消息：");
					}
				}, false);
				
				/**
				 * 模拟推送receive事件 勿删
				 */
				/*setInterval(function() {
					var MSGaaa = {
						msgtype: 1,
						msginfo: {
							id: '23', // 对方id
							uname: '金池', // 对方昵称
							msgcontent : '你好',
							time : '12-10 11:21'
						}
					}
					var msgType = MSGaaa.msgtype;
					var msgInfo = MSGaaa.msginfo;
					if(msgType == 1) { // 消息类型为私信消息
						mui.toast('消息类型为私信消息');
						var chatPage = plus.webview.getWebviewById('single-chat.html');
						if(!chatPage) { // 不在聊天窗口（或在与他人聊天的窗口） 创建本地消息 
							mui.toast('不在聊天窗口');
							$notice.show();
							// 本地创建标准格式消息，用于触发click事件
							mui.toast('创建本地消息');
							var createMsg = { // 这是本地创建标准格式的payload部分
								msgtype: msgType,
								msginfo: {
									id: msgInfo.id, // 对方id
									uname: msgInfo.uname // 对方昵称
								}
							}
							plus.push.createMessage(msgInfo.msgcontent, JSON.stringify(createMsg), {
								title: msgInfo.uname
							});
						} else { // 在当前窗口 将msginfo传至chat.html即可
							mui.toast('在聊天窗口，将msginfo传至chat.html');
							mui.fire(chatPage, 'getMessage', {
								msg : MSGaaa
							});
						}
					} else { // 系统消息，活动消息，直接本地创建标准格式
						mui.toast('消息类型不是私信消息');
						var createMsg = { // 这是本地创建标准格式的payload部分
							msgtype: msgType,
							msginfo: {
								id: msgInfo.id, // 对方id
								uname: msgInfo.uname // 对方昵称
							}
						}
						plus.push.createMessage(msgInfo.msgcontent, JSON.stringify(createMsg), {
							title: msgInfo.uname
						});
					}
				}, 5000)*/

				/**
				 * 
				 * 检查网络状态，若网络状态不正常，
				 * 若未连接网络将无法使用app
				 * 将来要监听网络状态变化
				 */
				
				/*var types = {}; 
				types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection"; 
				types[plus.networkinfo.CONNECTION_NONE] = "Ethernet None"; 
				types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection"; 
				types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection"; 
				types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection"; 
				types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection"; 
				types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection"; 

				mui.toast( "Network: " + types[plus.networkinfo.getCurrentType()]);*/
				
				// 检查更新
				setTimeout(function() {
					if(Common.getUniSetting() && Common.getUniSetting().autoUpdate) {
						Common.ajax({
//							url : baseURL + 'version/checkUpdate/1/' + plus.runtime.version + '.json'
							url : baseURL + 'version/checkUpdate/1/1.0.0.json'
						}, function(data) {
							if (data.code == 2) {
								plus.nativeUI.confirm("51帮办新版本已发布，是否立刻查看？", function(e) {
									if(!e.index) {
										plus.webview.create('pages/update.html', 'update', {}, {}).show('pop-in', 200);
									}
								}, '发现新版本', ["确定", "取消"]);
							}
						}, function(xhr) {
							
						})
					}
				}, 3000)
				
				var map = new plus.maps.Map("map");
				getCity();
				
				function getCity() {
					cityElem.innerText = '定位中';
					map.getUserLocation(function(state, point) {
						if(0 == state) {
							currentPosition = point;
							plus.maps.Map.reverseGeocode(point, {}, function(e) {
								Common.getCity(e.address, function(city) {
									city = cityElem.innerText = city;
									mui.toast('城市信息获取成功');
								}, function(data) {
									mui.toast('城市信息获取失败，请重试');
									getCityFail();
								})
							}, function() {
								getCityFail();
								mui.toast('定位信息获取失败，请重试');
							})
						} else {
							getCityFail();
							mui.toast('定位信息获取失败，请重试');
						}
					})
				}
				
				// 多次定位失败，不再重新定位
				var failCount = 0;
				function getCityFail() {
					failCount ++;
					cityElem.innerHTML = '定位失败';
					if(failCount <= 3) {
						plus.nativeUI.confirm("定位失败，请选择重新定位或手动选择？", function(e) {
							if(!e.index) {
								getCity();
							} else {
								plus.nativeUI.showWaiting();
								Common.openWindow('pages/city-list.html');
							}
						}, '', ["重新定位", "手动选择"]);
					} else {
						mui.toast('定位失败次数过多，请检查设备');
					}
				}
			
				//当前激活选项
				var activeTab = subpages[0];
				var titles = document.getElementById("defaultTab");
	
				// 选项卡点击事件
				mui('.mui-bar-tab').on('tap', 'a', function(e) {
					var detailPage = plus.webview.getWebviewById('home');
					var targetTab = this.getAttribute('href');
					if(targetTab == activeTab) {
						return;
					}
					//显示目标选项卡
					//若为iOS平台或非首次显示，则直接显示
					if(mui.os.ios || aniShow[targetTab]) {
						plus.webview.show(targetTab);
					} else {
						//否则，使用fade-in动画，且保存变量
						var temp = {};
						temp[targetTab] = "true";
						mui.extend(aniShow, temp);
						plus.webview.show(targetTab, "fade-in", 300);
					}
	
					//隐藏当前;
					plus.webview.hide(activeTab);
					//更改当前活跃的选项卡
					activeTab = targetTab;
					switch(activeTab) {
						case 'pages/home.html':
							$("header").hide().filter('#header1').show();
							break;
						case 'pages/artist.html':
							$("header").hide().filter('#header1').show();
							break;
						case 'pages/artshow.html':
							$("header").hide().filter('#header1').show();
							break;
						case 'pages/message.html':
							$("header").hide().filter('#header2').show();
							if($notice.is(':visible')) {
								$notice.hide();
							}
							break;
						case 'pages/me.html':
							$("header").hide().filter('#header3').show();
							break;
						default:
							break;
					}
				});
	
				// 点击输入框进入搜索页面
				mui('.form-search').on('click', 'input', function() {
					this.blur();
					plus.nativeUI.showWaiting();
					Common.openWindow('pages/search.html');
				})
	
				mui("header").on('tap', '#cityarea', function() {
					if($(this).find('#city').text() == '定位失败') {
						mui.toast('正在重新定位');
						getCity();
					} else {
						plus.nativeUI.showWaiting();
						Common.openWindow('pages/city-list.html');
					}
				})
				
				
				mui("header").on('tap', '#edit', function() {
					if(User.islogin()) {
						Common.openWindow('pages/release-artshow.html');
					} else {
						mui.toast('请先登录');
					}
				})
				
				//自定义事件，用于返回到指定的tab页
				document.addEventListener('goTab', function() {
					//获得返回的tab页的href
					var targetId = event.detail.targetTab;
					var targetTab = document.getElementById(targetId);
					//模拟首页点击
					mui.trigger(targetTab, 'tap');
					//切换选项卡高亮
					var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");
					if(targetTab !== current) {
						current.classList.remove('mui-active');
						targetTab.classList.add('mui-active');
					}
					if(event.detail.type == 'artistKey' || event.detail.type == 'artshowKey') {
						document.getElementById("search").value = plus.storage.getItem(event.detail.type);
						$("span.mui-icon-clear").removeClass('mui-hidden');
					}
					
					// index页转发筛选、查询数据至列表页
					if(targetId == 'artist') {
						var artistPage = self.children()[1];
						mui.fire(artistPage, event.detail.type, {});
					} else {
						var artshowPage = self.children()[2];
						mui.fire(artshowPage, event.detail.type, {});
					}
				});
				
				// 清空筛选条件
				document.addEventListener('clear', function() {
					document.getElementById("search").value = '';
				})
				
				// 改变城市
				document.addEventListener('changeCity', function() {
					cityElem.innerHTML = city = event.detail.city;
				})
				
				// 新的私聊消息
				document.addEventListener('newmsg', function() {
				})
				
				var backButtonPress = 0;
				mui.back = function(event) {
					backButtonPress++;
					if(backButtonPress > 1) {
						plus.runtime.quit();
					} else {
						plus.nativeUI.toast('再按一次退出 演得好');
					}
					setTimeout(function() {
						backButtonPress = 0;
					}, 1000);
					return false;
				};
			});
		</script>
	</body>

</html>